# test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
import glob
import os

# Register the streaming http handlers with urllib2
register_openers()

# requires / easy_install 'poster' egg
def post_file(url, file, *echo):
    # headers contains the necessary Content-Type and Content-Length
    # datagen is a generator object that yields the encoded parameters
    datagen, headers = multipart_encode({"doc": open(file, "rb")})

    # Create the Request object
    request = urllib2.Request(url, datagen, headers)

    # Actually do the request, and get the response
    open_url(request, echo)

def open_url(request, *echo):
    if echo and isinstance(request, str): print 'request: ' + request
    f = urllib2.urlopen(request)
    s = f.read()
    f.close()
    if echo: print 'reponse: ' + s

##
## iterate through .csv files in 'data' dir, and upload them to solr's csv loader
##
def upload_files(url, *echo):
    # rather stupid proper directory switch
    pwd = os.getcwd()
    if 'data' not in pwd:
        os.chdir(pwd + '/data')

    # ...
    fileNames = glob.glob("*.csv")
    for csv in fileNames:
        post_file(url, csv, echo)

upload_files("http://localhost:8080/solr/update/csv", False)
post_file("http://localhost:8080/solr/update", "commit.xml");
post_file("http://localhost:8080/solr/update", "optimize.xml");
open_url("http://localhost:8080/solr/select?qt=dismax&q=Nye",True);
